<?php

class grooveshark {

	private $api_key = 'd080c7840d7b1c7b677741bb8989a822';
	// tinysong has different lettered endpoints, see http://tinysong.com/api for full list
	private $endpoint = 'http://tinysong.com/b';
	
	// queries tinysong and returns formatted result
	private function get_json($query) {
		$json_url = "{$this->endpoint}/$query/?format=json&key={$this->api_key}";
		return json_decode(file_get_contents($json_url));
	}
	
	private function search_song($song, $artist, $album) {
		$song = prep_search_string($song);
		$artist = prep_search_string($artist);
		$album = prep_search_string($album);
		
		return $this->get_json("$artist+$song+$album");
	}
	
	// go through full json result as returned by search_song and return the first result's id
	private function get_song_id($song, $artist, $album) {	
		$song_json = $this->search_song($song, $artist, $album);
		if ($song_json->SongID)
			return $song_json->SongID;
		else
			return false;
	}
	
	public function render_player($song, $artist, $album) {
		$width = 'width="350"';
		$height = 'height="40"';
		$swf_url = 'http://listen.grooveshark.com/songWidget.swf';
		$vars = 'style=metal&p=1&hostname=cowbell.grooveshark.com';
		$song_id = $this->get_song_id($song, $artist, $album);
		if ($song_id) {
			echo '<object '.$width.$height.'>';
				echo '<param name="movie" value="'.$swf_url.'" />';
				echo '<param name="allowScriptAccess" value="always" /><param name="wmode" value="window" />';
				echo '<param name="flashvars" value="'.$vars.'&songIDs='. $song_id .'" />';
				echo '<embed src="'.$swf_url.'" '.$width.$height.' flashvars="'.$vars.'&songIDs='. $song_id .'" />';
			echo '</object>';
		} else
			return 'try hitting "close" and "play" again';
	}	

}

?>